#!/bin/bash
exec 2>/dev/console
exec 1>/dev/console
# Print some verbose output
echo
echo "        --- Apple TV Patchstick ---"
echo "        http://code.google.com/p/atvusb-creator"
echo "               * mounting OSBoot partition"
# Create a directory (OsBoot) to mount the OsBoot partition in.
mkdir -p /OSBoot
# Initialise the HFS+ fs
fsck.hfsplus -f /dev/sda3
# Mount the OsBoot partition to OsBoot directory.
mount -t hfsplus -o rw,force /dev/sda3 /OSBoot
# Wait for 1s so command next if statement does not execute before mount occurs.
sleep 1
# if we successfully mount /OSBoot 
if [ -d "/OSBoot/dev" ]; then
	# symlink /mnt/rootfs to /payloads to make the scripts easier to read
	echo "       * symlinking /mnt/rootfs -> /payloads"
	ln -s /mnt/rootfs/payloads /payloads

	echo "       * keeping the OSBoot partition r/w for plugins"
	touch /OSBoot/.readwrite

	echo "       * mounting Media partition"
     # Initalise the HFS+ fs
	fsck.hfsplus -f /dev/sda4
     # Mount the Media parititon to the mnt folder in OsBoot
	mount -t hfsplus -o rw,force /dev/sda4 /OSBoot/mnt
# Wait for 1ms so command next if statement does not execute before mount occurs.
	sleep 1
	if [ -d "/OSBoot/Users/frontrow" ]; then
		echo "       * create staging directory for install scripts"
		mkdir -p /OSBoot/Users/frontrow/staging
		ln -s /OSBoot/Users/frontrow/staging /staging
		#Run all install scripts in payloads directory.
		for script in $( find /payloads/ -name install.sh -print ); do
 			/bin/bash "${script}" 
			sleep 1
		done
	else 
		echo "       * error mounting Media partition"
	fi	
else 
	echo "       * error mounting OSBoot partition"
fi

if [ -d "/OSBoot/Users/frontrow/staging" ]; then
	echo "       * removing staging directory"
	rm -rf /OSBoot/Users/frontrow/staging
fi
sync
umount /OSBoot/mnt
umount /OSBoot
echo "       * Congratulations, the patchstick was succcessful"
echo
echo "       * Please remove the USB device used to patchstick this Apple TV and unplug Apple TV."
echo
echo "       * If you see no errors above you can then plug Apple TV back in"
echo
echo "       * If you chose to enable SSH, the username and password are both frontrow. The hostname is AppleTV.local. We recommend you use Cyberduck and Terminal for Mac and WinSCP and Putty for Windows."
echo
echo "       * Thank you for using Apple TV Patchstick Creator, for questions or the latest software please see: "
echo "         http://code.google.com/p/atvusb-creator"
echo
echo "Written by Scott Davilla"
echo "Updated by Sam Nazarko: 25/01/2010"
# Another blank line can't hurt
echo 
